package com.lanou.realm;

import com.lanou.bean.User;
import com.lanou.mapper.BlogMapper;
import com.lanou.mapper.UserMapper;
import com.lanou.service.UserService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by dllo on 18/3/7.
 */
public class MyPerRealm extends AuthorizingRealm {
    @Resource
    private UserMapper userMapper;


    @Override
    public boolean supports(AuthenticationToken token) {
        return token instanceof UsernamePasswordToken;
    }

    @Override
    public String getName() {
        return "MyPerRealm";
    }

    //授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        System.out.println("授权开始！");
        //***************假数据开始**********
        List<String> permissionList = new ArrayList<>();
        permissionList.add("user:create");
        permissionList.add("user:query");

        List<String> roleList = new ArrayList<>();
        roleList.add("CEO");
        roleList.add("DE");
        //***************假数据结束**********

        //授权信息对象，用来保存所有角色和授权信息
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        info.addRoles(roleList);
        info.addStringPermissions(permissionList);

        return info;
    }

    //认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
//        System.out.println("开始认证！！！");
        //获取token中的用户名
        String username = (String) authenticationToken.getPrincipal();
//        System.out.println(username);
        User user = userMapper.searchUserByUserName(username);
        if (user == null) {
            throw new UnknownAccountException("账号异常/不存在");
        }
        //获取token中的密码
        String password = new String((char[]) authenticationToken.getCredentials());
        if (!password.equals(user.getPassword())) {
            throw new IncorrectCredentialsException("密码错误");
        }

        return new SimpleAuthenticationInfo(username, password, getName());
    }
}
